/************************************************************/
/***************************定义变量*************************/
/** ********************************************************* */
// jQueryEasyUI对象变量
var jQueryEasyUI;
var datagridJQueryFind = "#dataGrid";
var dataFormDiv = "#dataForm";
var roleUserManagementF = "#roleUserManagementF";
var baseRequestUrl = '/dashu-authority/user';
var roleUrl = '/dashu-authority/roleController';
var formsubmitUrl;
var token=getQueryStr("DASHU_AUTH_TOKEN");
var auth=getQueryStr("auth");
var userManagementData = {
	    formId: "#addUserManagementF",
	    formSubmitUrl: "",
	    roleString: [],
	    usertypeArr: [],
	    usergroupArr: []
	};
$(function() {
	initDataGrid();
	$("#search").click(function() {
		var param = $.fn.getFormParams(searchFrom);
		$(datagridJQueryFind).datagrid('options').queryParams = param;
		$(datagridJQueryFind).datagrid('reload');
	});
	$("#clearBtn").click(function() {
		clearFrom(searchFrom);
	});
	$("#dlgDIV").hide();
	$("#roleUserManagement").hide();
	$.fn.datebox.defaults.formatter = function(date){
		var y = date.getFullYear();
		var m = date.getMonth()+1;
		var d = date.getDate();
		return m+'-'+d+'-'+y;
	}
	
	$("#rightRemoveUm").click(function () {
	    var removeItems = removeRoleUm("#leftSelUm", "#rightSelUm");
	    userManagementData.roleString = userManagementData.roleString.concat(removeItems);
	});

	$("#leftRemoveUm").click(function () {
		alert("leftRemoveUm");
	    var i;
	    var j;
	    var arr = userManagementData.roleString;
	    var removeItems = removeRoleUm("#rightSelUm", "#leftSelUm");
	    for (i = 0; i < removeItems.length; i++) {
	        for (j = 0; j < arr.length; j++) {
	            if (removeItems[i] == arr[j]) {
	                arr.splice(j, 1);
	            }
	        }
	    }
	    userManagementData.roleString = arr;
	});

});

function initDataGrid() {
	$(datagridJQueryFind).datagrid({
		loadMsg:"数据加载中，请稍后……",
		url : baseRequestUrl+'/findAllByPaging.json?DASHU_AUTH_TOKEN='+token,
		toolbar : [{
			id :'button6',
			text : '添加',
			iconCls : 'icon-add',
			handler : function() {
				formsubmitUrl = baseRequestUrl+'/save.json?DASHU_AUTH_TOKEN='+token;
				setDialog("#dlgDIV", '','新增');
				clearFrom(dataFormDiv);
				$("#dlgDIV").show();
			}
		},'-',{
			id :'button7',
			text : '编辑',
			iconCls : 'icon-edit',
			handler : function() {
				var row = $(datagridJQueryFind).datagrid("getSelected");
				if (row) {
					setDialog("#dlgDIV",'','编辑');
					$("#dlgDIV").show();
					clearFrom(dataFormDiv);
					//加载数据
					$(dataFormDiv).form('load',row);
					
					
					formsubmitUrl = baseRequestUrl+'/update.json?DASHU_AUTH_TOKEN='+token;
				} else {
					$.messager.alert("操作提示", "请选择一行", "info");
				}
			}
		},'-',{
			id :'button8',
			text : '删除',
			iconCls : 'icon-cancel',
			handler : function() {
				var rows = $(datagridJQueryFind).datagrid("getSelections");
				if (rows.length == 0 ) {
					$.messager.alert("操作提示", "请至少选择一行", "info");
				} else {
					var ids = [];
					for (var i = 0; i < rows.length; i++) {
						ids.push(rows[i].id);
					}
					$.messager.confirm('确认','您确认想要删除记录吗？',function(r) {
						if (r) {
							$.ajax({
								type : "POST",
								dataType : 'html',
								url : baseRequestUrl+'/deleteByIds.json?DASHU_AUTH_TOKEN='+token+'&ids='+ids,
								success : function(data) {
									var obj = eval('('+ data+ ')');
									console.log(JSON.stringify(obj));
									if (obj.status == 1) {
										$.fn.messageInfoTip(data);
										$(datagridJQueryFind).datagrid('reload');
									}
								},
								error: function(textStatus){
									if(console){
										console.error("ajax出现异常："+textStatus);
									}
									alert(textStatus);
								}
							});
						}else{
							return false;
						}
					});
				}
		}},'-',{
			id :'button9',
			text : '批量启动',
			iconCls : 'icon-ok',
			handler : function() {
				var rows = $(datagridJQueryFind).datagrid("getSelections");
				if (rows.length == 0 ) {
					$.messager.alert("操作提示", "请至少选择一行", "info");
				} else {
					var ids = [];
					for (var i = 0; i < rows.length; i++) {
						ids.push(rows[i].id);
					}
					$.messager.confirm('确认','您确认想要批量启动吗？',function(r) {
						if (r) {
							$.ajax({
								type : "POST",
								dataType : 'html',
								url : baseRequestUrl+'/updateStatus.json?DASHU_AUTH_TOKEN='+token+'&ids='+ids+'&status=1',
								success : function(data) {
									var obj = eval('('+ data+ ')');
									console.log(JSON.stringify(obj));
									if (obj.status == 1) {
										$.fn.messageInfoTip(data);
										$(datagridJQueryFind).datagrid('reload');
									}
								},
								error: function(textStatus){
									if(console){
										console.error("ajax出现异常："+textStatus);
									}
									alert(textStatus);
								}
							});
						}else{
							return false;
						}
					});
				}
		}},'-',{
			id :'button10',
			text : '批量停用',
			iconCls : 'icon-cancel',
			handler : function() {
				var rows = $(datagridJQueryFind).datagrid("getSelections");
				if (rows.length == 0 ) {
					$.messager.alert("操作提示", "请至少选择一行", "info");
				} else {
					var ids = [];
					for (var i = 0; i < rows.length; i++) {
						ids.push(rows[i].id);
					}
					$.messager.confirm('确认','您确认想要批量停用吗？',function(r) {
						if (r) {
							$.ajax({
								type : "POST",
								dataType : 'html',
								url : baseRequestUrl+'/updateStatus.json?DASHU_AUTH_TOKEN='+token+'&ids='+ids+'&status=0',
								success : function(data) {
									var obj = eval('('+ data+ ')');
									console.log(JSON.stringify(obj));
									if (obj.status == 1) {
										$.fn.messageInfoTip(data);
										$(datagridJQueryFind).datagrid('reload');
									}
								},
								error: function(textStatus){
									if(console){
										console.error("ajax出现异常："+textStatus);
									}
									alert(textStatus);
								}
							});
						}else{
							return false;
						}
					});
				}
		}},'-',{
			id :'button11',
			text : '绑定角色',
			iconCls : 'icon-cancel',
			handler :  function() {
				var row = $(datagridJQueryFind).datagrid("getSelected");
				if (row) {
//					setDialog("#roleUserManagement",'','绑定角色');
//					$("#roleUserManagement").show();
					clearFrom(roleUserManagementF);
					//加载数据
					changeRoleUserManagement(row.id,row.userName);
				} else {
					$.messager.alert("操作提示", "请选择一行", "info");
				}
			}}],
		width : '80%',
		pagination : true,
		pageSize : 10,
		singleSelect : false,
		striped : true,
		sortOrder : 'asc',
		rownumbers : true,
		loadFilter:function(data){
			return data.data;
		},
		onLoadSuccess : function() {
			$(datagridJQueryFind).datagrid('clearSelections');
			for(var i=6;i<=32;i++){
				if (!checkProduct(auth,i)) {
					var buttonId ="#button"+i;
					if ($(buttonId)) {
						$(buttonId).hide();
					}
					
				}
			}
		},
		onLoadError : function() {
		},
		columns : [ [ 
		       {	field : 'id',
					title : 'ID',
					width : 65,
					align : 'center',
					hidden : true,
					sortable : true
				}, {
					field : 'userName',
					title : '用户姓名',
					width : 90,
					align : 'center',
					sortable : true
				},{
					field : 'phoneNo',
					title : '电话号码',
					width : 90,
					align : 'center',
					sortable : true
				},{
					field : 'weChat',
					title : '微信号',
					width : 90,
					align : 'center',
					sortable : true
				},{
					field : 'email',
					title : '电子邮箱',
					width : 90,
					align : 'center',
					sortable : true
				},{
					field : 'loginId',
					title : '用户账号',
					width : 90,
					align : 'center',
					sortable : true
				},{
					field : 'password',
					title : '密码',
					width : 90,
					align : 'center',
					sortable : true
				},{
					field : 'postalCode',
					title : '邮编',
					width : 90,
					align : 'center',
					sortable : true
				},{
					field : 'status',
					title : '状态',
					width : 90,
					align : 'center',
					formatter:function(value,row,index){
						if("1"==value){
							return "启动"; 
						}
						return "停用";
					},
					sortable : true
				},{
					field : 'isSuperAdmin',
					title : '超级管理员',
					width : 90,
					align : 'center',
					formatter:function(value,row,index){
						if("1"==value){
							return "是"; 
						}
						return "否";
					},
					sortable : true
				},{
					field : 'createTime',
					title : '创建时间 ',
					width : 180,
					align : 'center',
					sortable : true
				}, {
					field : 'updateTime',
					title : '更新时间 ',
					width : 180,
					align : 'center',
					sortable : true
				}
		         ] ]
	});
}


function clearFrom(cform){
	$(cform).form("clear");
}

function submitForm() {
	$('#dataForm').form('submit', {
		url : formsubmitUrl,
		ajax : true,
		onSubmit:function(){
			return $(this).form('validate');
		},
		success : function(data) {
			var obj = eval('(' + data + ')');
			var status = obj.status;
			console.log(JSON.stringify(obj));
			if (status == 1) {
				$.fn.messageInfoTip(data);
				$('#dlgDIV').dialog('close');
				$(datagridJQueryFind).datagrid('reload');
			}else {
				$.fn.messageInfoTip(data);
//				$('#dlgDIV').dialog('close');
			}
		}
	});
}
//加载下拉框数据
function setComboboxData(id,url){
	$.ajax({
		type:"POST",
		dataType:'html',
		url:url,
		success:function(data){
			var obj = eval('('+ data+ ')');
			if (obj.status == 1) {
				$(id).combobox("loadData",obj.data);
			}
		},
		error:function(textStatus){
			if(console){
				console.error("ajax出现异常:"+textStatus);
			}
			alert(textStatus);
		}
	});
}
function setDialog(dialogDiv, hrefHtml, title) {
	$(dialogDiv).show();
	$(dialogDiv).dialog({
		title : title,
		width : 600,
		height : 400,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '保存',
			iconCls : 'icon-ok',
			handler : function() {
				submitForm();
			}
		}, {
			text : '重置',
			iconCls : 'icon-clear',
			handler : function() {
				clearFrom(dataFormDiv);
			}
		}, {
			text : '关闭',
			iconCls : 'icon-remove',
			handler : function() {
				$(dialogDiv).dialog('close');
			}
		} ]
	});
}

function removeRoleUm(from, to) {
    var i;
    var removeItems = [];
    var options = $(from).find("option:selected");
    for (i = 0; i < options.length; i++) {
        options.get(i).remove();
        var objRightSel = $(to).get(0);
        var option = new Option(options[i].text, options[i].value);
        objRightSel.options.add(option);
        removeItems.push(options[i].value);
    }
    return removeItems;
}

function changeRoleUserManagement(id, userName) {
	$("#roleUserManagement").find("h4").html("用户：" + userName);
    $("#leftSelUm, #rightSelUm").html("");
    userManagementData.roleString = "";
    $.ajax({
		type : "POST",
		dataType : 'json',
		url : roleUrl+'/findAllByUserId.json?DASHU_AUTH_TOKEN='+token+'&userId='+id,
		success : function receive(data) {
	        var i;
	        var arr = [];
	        var rows = data.data.rows;
	        var objRightSel = $("#rightSelUm").get(0);
	        if (Array.isArray(rows)) {
	            for (i = 0; i < rows.length; i++) {
	                var option = new Option(rows[i].roleName, rows[i].id);
	                objRightSel.options.add(option);
	                arr.push(rows[i].id);
	            }
	        }
	        userManagementData.roleString = arr;
	    },
		error: function(textStatus){
			if(console){
				console.error("ajax出现异常："+textStatus);
			}
			alert(textStatus);
		}
	});
        
    $.ajax({
		type : "POST",
		dataType : 'json',
		url : roleUrl+'/findAllByNoUserId.json?DASHU_AUTH_TOKEN='+token+'&userId='+id,
		success : function receive(data) {
	        var i;
	        var rows = data.data.rows;
	        var objLeftSel = $("#leftSelUm").get(0);
	        if (Array.isArray(rows)) {
	            for (i = 0; i < rows.length; i++) {
	                var option = new Option(rows[i].roleName, rows[i].id);
	                objLeftSel.options.add(option);
	            }
	        }
	    },
		error: function(textStatus){
			if(console){
				console.error("ajax出现异常："+textStatus);
			}
			alert(textStatus);
		}
	});
    $("#roleUserManagementF").form("load", {userId: id});
    $("#roleUserManagement").show().dialog({
        title: "用户组角色页面",
        width: 600,
        height: 500,
        cache: false,
        buttons: [{
            text: "保存",
            iconCls: "icon-ok",
            handler: function () {
                submitRoleUserManagement();
            }
        },{
            text: "关闭",
            iconCls: "icon-remove",
            handler: function () {
                $("#roleUserManagement").dialog("close");
            }
        }]
    });
}

function submitRoleUserManagement() {
    userManagementData.roleString = userManagementData.roleString.toString();
    $("#roleUserManagementF").form("submit", {
        url: baseRequestUrl+'/saveUserAndRole.json?DASHU_AUTH_TOKEN='+token,
        onSubmit: function (param) {
            param.roleIds = userManagementData.roleString;
            return $(this).form("validate");
        },
        success: function (data) {
            var obj = eval("(" + data + ")");
            $("#roleUserManagement").dialog("close");
            $("#userManagementTable").datagrid("reload");
            $.fn.messageInfoTip(obj);
        }
    });
}